<template>
	<up-popup :show="show" @close="handleClose" round="12">
		<view class="popup-wrap" :class="{ popup: isChoose }">
			<view class="header" :class="{ 'new-header': !isChoose }">
				<view class="new" @click="newInfo" v-if="isChoose">新增</view>
				<view class="title">{{ textObj.title }}</view>
				<image :src="`${imgBaseUrl}close-icon.png`" class="close-icon" @click="handleClose" />
			</view>
			<view v-if="isChoose" class="list-wrap">
				<view
					class="info-card"
					v-for="item in contactsList"
					:key="item.id"
					@click="handleContactsCheck(item.id)"
				>
					<image
						:src="`${imgBaseUrl}${checkedContactsId === item.id ? 'checked' : 'uncheck'}-icon.png`"
						class="check"
					/>
					<view class="infos">
						<view class="info name">{{ item.name }}</view>
						<view class="info">{{ item.id_value }}</view>
						<view class="info">{{ item.mobile }}</view>
					</view>
					<image :src="`${imgBaseUrl}edit-icon.png`" class="edit" @click.stop="editContactsInfo(item.id)" />
				</view>
			</view>
			<template v-else>
				<view class="fields">
					<view class="label">证件类型</view>
					<text class="content" @click="togglePickerShow">{{ idTypeText }}</text>
				</view>
				<view class="box">
					<view class="fields-wrap">
						<view class="fields">
							<view class="label">
								<text class="required">*</text>
								姓名
							</view>
							<view class="content">
								<up-input
									placeholder="请输入证件上姓名"
									border="none"
									placeholder-class="ipt-placeholder"
									v-model="contactsInfos.name"
									@focus="handleFocus"
									@blur="handleBlur"
								></up-input>
							</view>
						</view>
						<view class="fields id-fields">
							<view class="label">
								<text class="required">*</text>
								证件号
							</view>
							<view class="content">
								<up-input
									:type="contactsInfos.id_type === 10 ? 'idcard' : 'text'"
									placeholder="请输入证件号"
									border="none"
									placeholder-class="ipt-placeholder"
									v-model="contactsInfos.id_value"
									@focus="handleFocus"
									@blur="handleBlur"
								></up-input>
							</view>
						</view>
					</view>
					<view class="ocr">
						<image :src="`${imgBaseUrl}ocr-icon.png`" class="ocr-icon" />
						<text>拍照识别</text>
					</view>
				</view>

				<view class="fields phone-fields">
					<view class="label">
						<text class="required">*</text>
						手机号
					</view>
					<view class="content">
						<up-input
							type="number"
							placeholder="输入联系人手机号"
							border="none"
							placeholder-class="ipt-placeholder"
							v-model="contactsInfos.mobile"
							@focus="handleFocus"
							@blur="handleBlur"
						></up-input>
					</view>
				</view>
			</template>

			<view class="bottom">
				<zjy-button @click="handleClick">{{ textObj.btnText }}</zjy-button>
			</view>
		</view>
		<up-picker
			:show="pickerShow"
			:columns="[idTypeColumn]"
			key-name="label"
			close-on-click-overlay
			:default-index="defaultIndex"
			@close="togglePickerShow"
			@cancel="togglePickerShow"
			@confirm="handlePickerConfirm"
		></up-picker>
	</up-popup>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watchEffect } from "vue"
import { $getContactsList, $addContacts, $updateContacts } from "@/api/ticket"
import type { ContactsInfo } from "@/types/ticket"

interface TouristContactProps {
	show: boolean
	idx?: number
	// tourist: 游客 contact: 联系人
	type: "tourist" | "contact"
}

const props = defineProps<TouristContactProps>()
const emit = defineEmits(["contact-info-change", "close-popup"])
const imgBaseUrl = inject("imgBaseUrl")

const idTypeColumn = [
	{
		label: "身份证",
		value: 10,
	},
	{
		label: "护照",
		value: 20,
	},
	{
		label: "港澳通行",
		value: 30,
	},
	{
		label: "永居证",
		value: 40,
	},
	{
		label: "军官证",
		value: 50,
	},
	{
		label: "其他",
		value: 60,
	},
]

const pickerShow = ref(false)
// 操作类型，choose: 选择 new: 新增 edit: 编辑
const opType = ref<"choose" | "new" | "edit">("choose")
// 联系人列表
const contactsList = ref<ContactsInfo[]>([])
// 选中的联系人的 id
const checkedContactsId = ref<number | null>(null)
// 联系人信息
const contactsInfos = reactive({
	// 证件类型
	id_type: 10,
	name: "",
	// 证件号
	id_value: "",
	// 手机号
	mobile: "",
})
const defaultIndex = ref<number[]>([0])
const id = ref(0)
const focus = ref(false)

const isChoose = computed(() => opType.value === "choose")
const textObj = computed(() => ({
	title: { choose: "选择游客", new: "新增常用游客", edit: "修改常用游客" }[opType.value],
	btnText: { choose: "确定", new: "保存", edit: "保存" }[opType.value],
}))
const idTypeText = computed(() => idTypeColumn.find((item) => item.value === contactsInfos.id_type)?.label)

const closePopup = () => {
	checkedContactsId.value = null

	emit("close-popup")
}
const newInfo = () => (opType.value = "new")

const handleFocus = () => (focus.value = true)
const handleBlur = () => (focus.value = false)

watchEffect(() => {
	if (props.show) {
		openPopup()
	}

	uni.$emit("submit-order-popup-visible", props.show)
})

const getContactsList = async () => {
	const data = await $getContactsList()
	contactsList.value = (data as { list: [] }).list
}

const openPopup = async () => {
	await getContactsList()

	// 没有联系人，直接到新增页面
	if (!contactsList.value.length) {
		opType.value = "new"
	}
}

const resetContactsInfos = () => {
	contactsInfos.id_type = 10
	contactsInfos.name = ""
	contactsInfos.id_value = ""
	contactsInfos.mobile = ""
}

const handleClose = () => {
	if (focus.value) return

	if (opType.value === "new" || opType.value === "edit") {
		opType.value = "choose"

		resetContactsInfos()
		return
	}

	closePopup()
}

const handleClick = async () => {
	if (opType.value === "new") {
		await $addContacts({ data: JSON.stringify(contactsInfos) })

		await getContactsList()

		opType.value = "choose"

		resetContactsInfos()
		return
	}

	if (opType.value === "choose") {
		if (!checkedContactsId.value) {
			uni.showToast({
				icon: "none",
				title: {
					tourist: "请选择游客",
					contact: "请选择联系人",
				}[props.type],
			})

			return
		}

		const result = checkedContactsId.value
			? contactsList.value.find((item) => item.id === checkedContactsId.value)
			: null

		emit("contact-info-change", {
			id_type: result?.id_type,
			id_value: result?.id_value,
			name: result?.name,
			mobile: result?.mobile,
		})

		closePopup()

		return
	}

	if (opType.value === "edit") {
		await $updateContacts(id.value, { data: JSON.stringify(contactsInfos) })

		await getContactsList()

		opType.value = "choose"

		resetContactsInfos()
	}
}

const togglePickerShow = () => (pickerShow.value = !pickerShow.value)

const handlePickerConfirm = (data: { value: typeof idTypeColumn }) => {
	contactsInfos.id_type = data.value[0].value

	togglePickerShow()
}

const handleContactsCheck = (id: number) => {
	if (checkedContactsId.value === id) {
		checkedContactsId.value = null
		return
	}

	checkedContactsId.value = id
}

const editContactsInfo = (contact_id: number) => {
	const needEditInfo = contactsList.value.find((item) => item.id === contact_id)

	if (needEditInfo) {
		contactsInfos.id_type = needEditInfo.id_type
		contactsInfos.name = needEditInfo.name
		contactsInfos.id_value = needEditInfo.id_value
		contactsInfos.mobile = needEditInfo.mobile

		id.value = contact_id

		defaultIndex.value = [idTypeColumn.findIndex((item) => item.value === needEditInfo.id_type)]

		opType.value = "edit"
	}
}
</script>

<script lang="ts">
export default {
	options: { styleIsolation: "shared" },
}
</script>

<style lang="scss" scoped>
.popup-wrap {
	position: relative;
	padding: 30rpx 24rpx 128rpx;

	&.popup {
		background-color: #f7f8f9;
		border-radius: 24rpx;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;

		&.new-header {
			margin-bottom: 32rpx;
		}

		.new {
			font-size: 28rpx;
			color: #bc8400;
			line-height: 40rpx;
		}

		.title {
			flex: 1;
			font-weight: 600;
			font-size: 36rpx;
			color: #000000;
			line-height: 36rpx;
			text-align: center;
		}

		.close-icon {
			width: 48rpx;
			height: 48rpx;
		}
	}

	.tips {
		margin-top: 14rpx;
		font-size: 24rpx;
		color: #c9cdd4;
		line-height: 34rpx;
		text-align: center;

		.number {
			color: #bc8400;
		}
	}

	.list-wrap {
		max-height: 40vh;
		overflow-y: auto;
		margin-top: 48rpx;
	}

	.info-card {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 16rpx;
		padding: 40rpx;
		padding-right: 32rpx;
		border-radius: 16rpx;
		background-color: #fff;

		&:last-child {
			margin-bottom: 0;
		}

		.check {
			width: 40rpx;
			height: 40rpx;
		}

		.infos {
			flex: 1;
			margin: 0 48rpx;
			font-size: 28rpx;
			color: #86909c;
			line-height: 40rpx;

			.info {
				margin-bottom: 8rpx;

				&:last-child {
					margin-bottom: 0;
				}

				&.name {
					font-size: 32rpx;
					font-weight: 500;
					color: #1d2129;
					line-height: 44rpx;
				}
			}
		}

		.edit {
			width: 40rpx;
			height: 40rpx;
		}
	}

	.box {
		display: flex;
		align-items: center;

		.fields-wrap {
			flex: 1;
		}

		.ocr {
			// display: flex;
			display: none;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			width: 96rpx;
			margin-left: 100rpx;
			font-size: 24rpx;
			color: #bc8400;
			line-height: 34rpx;

			.ocr-icon {
				width: 48rpx;
				height: 48rpx;
				margin-bottom: 12rpx;
			}
		}
	}

	.fields {
		display: flex;
		align-items: center;
		padding: 32rpx 0;
		border-bottom: 1rpx solid #f3f3f3;

		&.id-fields {
			border-bottom: 0;
		}

		&.phone-fields {
			border-top: 1rpx solid #f3f3f3;
		}

		.label {
			min-width: 112rpx;
			font-size: 28rpx;
			color: #4e5969;
			line-height: 40rpx;

			.required {
				color: #f53f3f;
			}
		}

		.content {
			flex: 1;
			padding-left: 40rpx;
			font-size: 28rpx;
			color: #1d2129;
			line-height: 40rpx;
		}

		::v-deep .ipt-placeholder {
			font-size: 28rpx;
			color: #c9cdd4;
			line-height: 40rpx;
		}
	}

	.bottom {
		position: absolute;
		left: 0;
		bottom: 0;
		width: 100%;
		background-color: #fff;
		padding: 24rpx;
		padding-bottom: 0;

		::v-deep .zjy-button {
			font-weight: 600 !important;
		}
	}
}
</style>
